<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-header">
        <i class="el-icon-search"></i>
        <span>快速搜索</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="年级" prop="grade">
          <el-select v-model="queryParams.grade" placeholder="选择年级" clearable>
            <el-option
              v-for="item in gradeOptions"
              :key="item.grade"
              :label="item.grade + '级'"
              :value="item.grade"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班名" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入班名" clearable>
            <i slot="prefix" class="el-input__icon el-icon-school"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="班长" prop="leader">
          <el-input v-model="queryParams.leader" placeholder="请输入班长姓名" clearable>
            <i slot="prefix" class="el-input__icon el-icon-user"></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery" class="search-btn">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['manager:clazz:add']" class="action-btn">
        新增班级
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['manager:clazz:remove']" class="action-btn">
        批量删除
      </el-button>
    </div>

    <!-- 班级列表 - 使用卡片式布局 -->
    <el-row :gutter="20">
      <el-col :span="8" v-for="item in clazzList" :key="item.clazzId">
        <el-card class="clazz-card" shadow="hover">
          <!-- 卡片头部 -->
          <div class="clazz-header">
            <div class="header-left">
              <div class="grade-tag">
                <i class="el-icon-reading"></i>
                {{ item.grade }}级
              </div>
              <div class="number-tag">
                <i class="el-icon-user"></i>
                {{ item.number }}人
              </div>
            </div>
            <h3 class="clazz-name">{{ item.name }}</h3>
          </div>

          <!-- 卡片内容 -->
          <div class="clazz-body">
            <!-- 基本信息区域 -->
            <div class="clazz-info">
              <div class="info-item">
                <i class="el-icon-user"></i>
                <span class="label">班长姓名：</span>
                <span class="value">{{ item.leader }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-phone"></i>
                <span class="label">联系方式：</span>
                <span class="value">{{ item.phone }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-document"></i>
                <span class="label">备注信息：</span>
                <span class="value">{{ item.remark || '暂无' }}</span>
              </div>
            </div>
          </div>

          <!-- 卡片底部操作区 -->
          <div class="clazz-actions">
            <!-- 左侧 - 查看详情按钮 -->
            <div class="left-actions">
              <el-button 
                type="primary"
                plain
                icon="el-icon-view" 
                size="small"
                style="background: #ecf5ff; border-color: #b3d8ff;"
                @click="handleDetail(item)"
              >查看详情</el-button>
            </div>

            <!-- 右侧 - 其他操作按钮 -->
            <div class="right-actions">
              <el-tooltip content="编辑班级" placement="top">
                <el-button 
                  type="warning" 
                  icon="el-icon-edit" 
                  circle 
                  size="small" 
                  @click="handleUpdate(item)"
                ></el-button>
              </el-tooltip>

              <el-tooltip content="删除班级" placement="top">
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  size="small" 
                  @click="handleDelete(item)"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页器 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加/修改班级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body custom-class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="选择年级" class="custom-select">
            <el-option
              v-for="item in gradeOptions"
              :key="item.grade"
              :label="item.grade + '级'"
              :value="item.grade"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班名" prop="name">
          <el-input v-model="form.name" placeholder="请输入班名"/>
        </el-form-item>
        <el-form-item label="班长" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入班长姓名"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加分配学员对话框 -->
    <el-dialog 
      title="分配学员" 
      :visible.sync="assignDialogVisible" 
      width="600px"
      append-to-body
    >
      <!-- 搜索框 -->
      <div class="dialog-search">
        <el-form :inline="true">
          <el-form-item label="年级">
            <el-select v-model="studentSearchParams.grade" placeholder="选择年级" clearable @change="handleStudentSearch">
              <el-option
                v-for="item in gradeOptions"
                :key="item.grade"
                :label="item.grade + '级'"
                :value="item.grade"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="studentSearchParams.nickName"
              placeholder="输入姓名搜索"
              clearable
              @input="handleStudentSearch"
              class="search-input"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        ref="assignTable"
        :data="filteredStudentList"
        @selection-change="handleSelectionChange"
        height="400"
        v-loading="studentLoading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="学号" prop="studentId" width="120"></el-table-column>
        <el-table-column label="姓名" prop="nickName" width="120">
          <template slot-scope="scope">
            <span v-html="highlightKeyword(scope.row.nickName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="专业" prop="specialty"></el-table-column>
        <el-table-column label="联系方式" prop="phonenumber"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAssign">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClazz, getClazz, delClazz, addClazz, updateClazz ,assignPlayer,clazzDetails } from "@/api/manager/clazz/clazz";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { listGrade } from "@/api/manager/grade/grade";

export default {
  name: "Clazz",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 班级表格数据
      clazzList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 年级选项
      gradeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9,
        grade: null,
        name: null,
        leader: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        grade: [
          { required: true, message: "年级不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "班名不能为空", trigger: "blur" }
        ],
        leader: [
          { required: true, message: "班长不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系方式不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ]
      },
      assignDialogVisible: false,
      studentList: [],
      selectedStudents: [],
      currentClass: null,
      studentSearchParams: {
        grade: null,
        nickName: ''
      },
      studentLoading: false, // 加载状态
    };
  },
  computed: {
    // 修改过滤逻辑
    filteredStudentList() {
      const list = this.studentList;
      const { grade, nickName } = this.studentSearchParams;
      
      return list.filter(item => {
        const matchGrade = !grade || item.grade === grade;
        const matchName = !nickName || 
          (item.nickName && item.nickName.toLowerCase().includes(nickName.toLowerCase()));
        return matchGrade && matchName;
      });
    }
  },
  created() {
    this.getList();
    this.getGradeOptions();
  },
  methods: {
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      listClazz(this.queryParams).then(response => {
        this.clazzList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        clazzId: null,
        grade: null,
        name: null,
        number: null,
        leader: null,
        phone: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const clazzId = row.clazzId;
      getClazz(clazzId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班级信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.clazzId != null) {
            updateClazz(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClazz(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const clazzIds = row.clazzId || this.ids;
      this.$modal.confirm('是否确认删除班级编号为"' + clazzIds + '"的数据项？').then(function() {
        return delClazz(clazzIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 处理班级详情跳转
    handleDetail(row) {
      // 构造要传递的班级信息
      const classInfo = {
        clazzId: row.clazzId,
        grade: row.grade,
        name: row.name,
        leader: row.leader,
        phone: row.phone,
        number: row.number
      };
      
      this.$router.push({
        path: '/manager/clazz/detail',
        query: { 
          classInfo: JSON.stringify(classInfo)
        }
      });
    },
    
    // 处理分配学员
    handleAssignStudents(row) {
      this.currentClass = row;
      this.assignDialogVisible = true;
      // 重置搜索条件
      this.studentSearchParams = {
        grade: null,
        nickName: ''
      };
      this.studentLoading = true;
      
      // 修改查询参数，确保获取所有需要的字段
      listUser({
        grade: row.grade,
        pageSize: 999  // 获取所有数据
      }).then(response => {
        // 打印返回数据，用于调试
        console.log('学生列表数据:', response.rows);
        
        // 过滤掉已经分配到班级的学生
        this.studentList = response.rows.filter(student => {
          // 根据实际情况添加过滤条件
          return student.nickName && student.studentId;  // 确保基本信息存在
        });
        
        this.studentLoading = false;
      }).catch(() => {
        this.studentLoading = false;
        this.$modal.msgError("获取学生列表失败");
      });
    },
    
    // 处理学员选择变化
    handleSelectionChange(selection) {
      this.selectedStudents = selection;
    },
    
    // 确认分配学员
    confirmAssign() {
      if (this.selectedStudents.length === 0) {
        this.$modal.msgError("请选择要分配的学员");
        return;
      }
      
      const data = {
        userIds: this.selectedStudents.map(item => Number(item.userId)),
        clazzId: Number(this.currentClass.clazzId)
      };
      
      assignPlayer(data.userIds, data.clazzId).then(response => {
        this.$modal.msgSuccess("分配成功");
        this.assignDialogVisible = false;
        this.getList();
      }).catch(() => {
        this.$modal.msgError("分配失败");
      });
    },
    
    // 处理学员搜索
    handleStudentSearch() {
      this.$refs.assignTable.clearSelection();
      this.selectedStudents = [];
    },
    
    // 处理清除搜索
    handleStudentSearchClear() {
      this.studentSearchParams = {
        grade: null,
        nickName: ''
      };
      this.$refs.assignTable.clearSelection();
      this.selectedStudents = [];
    },
    
    // 修改高亮方法
    highlightKeyword(value) {
      if (!this.studentSearchParams.nickName || !value) {
        return value;
      }
      const key = this.studentSearchParams.nickName.toLowerCase();
      const index = value.toLowerCase().indexOf(key);
      if (index !== -1) {
        const start = value.slice(0, index);
        const middle = value.slice(index, index + key.length);
        const end = value.slice(index + key.length);
        return `${start}<span class="highlight-text">${middle}</span>${end}`;
      }
      return value;
    },
    // 添加获取年级选项方法
    getGradeOptions() {
      listGrade().then(response => {
        this.gradeOptions = response.rows;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  min-height: calc(100vh - 84px);
  
  // 使用渐变背景替代纯色背景
  background: linear-gradient(to bottom, #f6f8fb, #f0f2f5);
  
  // 添加网格背景增加层次感
  background-image: 
    linear-gradient(rgba(255, 255, 255, 0.8) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.8) 1px, transparent 1px);
  background-size: 20px 20px;
  background-position: center center;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.05);
  
  .search-header {
    margin-bottom: 20px;
    font-size: 16px;
    color: #303133;
    font-weight: bold;
    
    i {
      margin-right: 8px;
      color: #409EFF;
    }
  }

  .el-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.action-bar {
  margin: 20px 0;
  display: flex;
  gap: 10px;
  
  .action-btn {
    border-radius: 4px;
    padding: 8px 16px;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
    }
  }
}

.card-container {
  margin: 0 -10px;
}

.clazz-card {
  position: relative;
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  overflow: hidden;
  min-height: 250px;
  display: flex;
  flex-direction: column;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.08);
  }

  .clazz-header {
    margin-bottom: 20px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 8px;

      .grade-tag, .number-tag {
        display: inline-flex;
        align-items: center;
        padding: 4px 12px;
        border-radius: 4px;
        font-size: 13px;
        
        i {
          margin-right: 4px;
          font-size: 14px;
        }
      }

      .grade-tag {
        background: rgba(64, 158, 255, 0.1);
        color: #409EFF;
      }

      .number-tag {
        background: rgba(103, 194, 58, 0.1);
        color: #67C23A;
      }
    }

    .clazz-name {
      margin: 0;
      font-size: 18px;
      color: #303133;
      font-weight: 600;
    }
  }

  .clazz-body {
    flex: 1;
    
    .clazz-info {
      .info-item {
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        
        i {
          color: #409EFF;
          margin-right: 8px;
          font-size: 16px;
        }

        .label {
          color: #606266;
          margin-right: 8px;
          width: 80px;
        }

        .value {
          color: #303133;
          flex: 1;
        }
      }
    }
  }

  .clazz-actions {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-actions {
      .el-button {
        padding: 8px 15px;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }

    .right-actions {
      display: flex;
      gap: 8px;
      
      .el-button {
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
        }
        
        &.is-circle {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.custom-dialog {
  border-radius: 8px;
  
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-dialog__body {
    padding: 30px 20px;
  }
  
  .el-dialog__footer {
    padding: 20px;
    border-top: 1px solid #ebeef5;
  }
}

.custom-select {
  width: 100%;
}

// 响应式调整
@media screen and (max-width: 768px) {
  .class-card {
    margin: 10px 0;
  }
  
  .action-bar {
    flex-wrap: wrap;
  }
  
  .action-btn {
    width: 100%;
  }
}

.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  
  .el-input {
    width: 200px;
  }
}

// 高亮样式
:deep(.highlight) {
  color: #409EFF;
  font-weight: bold;
}

.el-dialog {
  .el-table {
    margin: 15px 0;
  }
}

.dialog-search {
  padding: 0 0 15px 0;
  border-bottom: 1px solid #ebeef5;
  
  .el-form {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .search-input {
    width: 220px;
  }
}

/* 修改高亮样式的写法，适配Vue2 */
:deep(.highlight-text) {
  color: #409EFF;
  font-weight: bold;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 0 2px;
}
</style>
